<template>
    <div class="main">
        <!-- top -->
        <div class="top">
            <el-form :model="form" label-width="auto" style="max-width: 100%">
                <el-row>
                    <el-form-item label="渠道名称">
                        <el-input v-model="form.channelName" placeholder="请输入渠道名称" />
                    </el-form-item>
                    <el-form-item label="渠道状态">
                        <el-select v-model="form.status" placeholder="渠道状态">
                            <el-option label="正常" :value="1" />
                            <el-option label="禁用" :value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="渠道类型">
                        <el-select v-model="form.type" placeholder="渠道类型">
                            <el-option label="线上渠道" :value="1" />
                            <el-option label="线下渠道" :value="2" />
                        </el-select>
                    </el-form-item>

                    <div class="demo-date-picker">
                        <div class="block">
                            <span class="demonstration">创建时间</span>
                            <el-date-picker v-model="dateRange" type="daterange" range-separator="-"
                                start-placeholder="开始日期" end-placeholder="结束日期" :size="size" format="YYYY/MM/DD"
                                value-format="YYYY-MM-DD" @change="handleDateChange"
                                style="width: 240px;margin-right: 32px;" />
                        </div>
                    </div>

                    <el-form-item>
                        <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
                        <el-button :icon="Refresh">重置</el-button>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-button type="primary" :icon="Plus" plain @click="add">新增</el-button>
                    <!-- :disabled="delId.length == 0":当delId的长度为0时禁用删除按钮 -->
                    <el-button type="success" :icon="Edit" plain @click="edit(null)"
                        :disabled="editId.length !== 1">修改</el-button>
                    <el-button type="danger" :icon="Delete" plain :disabled="editId.length == 0"
                        @click="del(null)">删除</el-button>
                    <el-button type="info" plain :icon="Upload" v-hasPermi="['system:user:import']"
                        @click="handleImport">导入</el-button>
                    <el-button type="warning" :icon="Download" plain @click="exportXLsx">导出</el-button>
                </el-row>
            </el-form>
        </div>
        <!-- center -->
        <div>
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column property="channelId" label="渠道编号" width="120">
                </el-table-column>
                <el-table-column property="channelName" label="渠道名称" width="150" />
                <el-table-column property="type" label="渠道类型" width="100">
                    <template #default="scope">
                        <el-tag type="primary" v-if="scope.row.type == 1">线上渠道</el-tag>
                        <el-tag type="success" v-if="scope.row.type == 2">线下渠道</el-tag>
                    </template>
                </el-table-column>
                <el-table-column property="status" label="渠道状态" width="100">
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
                        <el-tag type="info" v-if="scope.row.status == 0">禁用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column property="createBy" label="创建人" width="100" />
                <el-table-column property="createTime" label="创建时间" width="200" />
                <el-table-column property="remark" label="备注信息" width="180" />
                <el-table-column label="操作">
                    <template #default="scope">

                        <el-tooltip class="box-item" effect="dark" content="修改" placement="top">
                            <el-icon color="#409efc" class="no-inherit" @click="edit(scope.row.channelId)">
                                <Edit />
                            </el-icon>
                        </el-tooltip>
                        <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                            <el-icon color="#409efc" class="no-inherit" @click="del(scope.row.channelId)">
                                <Delete />
                            </el-icon>
                        </el-tooltip>
                    </template>

                </el-table-column>

            </el-table>
        </div>
        <!-- bottom -->
        <div class="demo-pagination-block">
            <el-pagination v-model:current-page="listParams.pageNum" v-model:page-size="listParams.pageSize"
                :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
        <!-- 添加&修改 -->
        <div>
            <el-dialog v-model="dialogVisible" :title="title" width="500">

                <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
                    <el-form-item label="渠道名称" prop="channelName">
                        <el-input v-model="ruleForm.channelName" />
                    </el-form-item>
                    <el-form-item label="渠道状态" prop="status">
                        <el-radio-group v-model="ruleForm.status">
                            <el-radio :label="1">正常</el-radio>
                            <el-radio :label="0">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="渠道类型" prop="type">
                        <el-radio-group v-model="ruleForm.type">
                            <el-radio :label="1">线上渠道</el-radio>
                            <el-radio :label="2">线下渠道</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="ruleForm.remark" type="textarea" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="dialogVisible = false">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
        <!-- 用户导入对话框 -->
        <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <div class="el-upload__tip">
                            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                        </div>
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                            @click="importTemplate">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, nextTick } from 'vue'
import { Search, Refresh, Plus, Download, Delete, Edit, Upload } from '@element-plus/icons-vue'
import { channelList, channelSearch, channelOut, channeAdd, channeEdit, channeEdits, channelDel } from '@/api/channel'
import type { ComponentSize, FormInstance, FormRules, TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCurrentInstance, ComponentInternalInstance, toRefs, watch } from 'vue';
import { getToken } from '@/utils/auth';
// top******************
const form = reactive({
    pageNum: 1,
    pageSize: 10,
    channelName: '',
    status: '',
    type: '',
    params: {
        beginTime: '',
        endTime: ''
    },
})
const dateRange = ref([]);
// 获取日期
function handleDateChange(dateValue: any) {
    if (dateValue && dateValue.length === 2) {
        form.params.beginTime = dateValue[0];
        form.params.endTime = dateValue[1];
    }
}
// 查询按钮
function searchList() {
    channelSearch(form).then(res => {
        console.log(res, "********************");
        tableData.value = res.rows
        total.value = res.total
    })
}
const search = (() => {
    listParams.pageNum = 1
    searchList()
})
// 添加按钮
const dialogVisible = ref(false)
const title = ref('')
const add = (() => {
    title.value = '添加渠道'
    dialogVisible.value = true
    // 重置表单
    nextTick(() => {
        ruleFormRef.value.resetFields()
    })
})
// ruleForm表单数据
interface RuleForm {
    channelName: string
    status: number | undefined
    type: number | undefined
    remark: string
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    channelName: '',
    status: undefined,
    type: undefined,
    remark: '',
})
const rules = reactive<FormRules<RuleForm>>({
    channelName: [
        { required: true, message: '渠道名称不能为空', trigger: 'blur' },
    ],
    status: [
        { required: true, message: '渠道状态不能为空', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '渠道类型不能为空', trigger: 'blur' },
    ]
})
// 导入按钮
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
/*** 用户导入参数 */
const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer ' + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/tienchin/channel/importData',
});
/** 导入按钮操作 */
function handleImport() {
    upload.title = '用户导入';
    upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
    proxy!.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
}
/**文件上传中处理 */
const handleFileUploadProgress = (event?: any, file?: any, fileList?: any) => {
    upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: any, fileList: any) => {
    upload.open = false;
    upload.isUploading = false;
    (proxy?.$refs['uploadRef'] as any).handleRemove(file);
    (proxy as any).$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true }
    );
    getList();
};
/** 提交上传文件 */
function submitFileForm() {
    (proxy?.$refs['uploadRef'] as any).submit();
}
// 导出按钮
const exportXLsx = (() => {
    channelOut(form).then(res => {
        console.log(res, "导出成功");
        // 创建一个blob对象，存储excel文件的数据
        let blob = new Blob([res])
        // 创建一个a标签
        const link = document.createElement("a")
        // 创建一个下载链接，并将其赋值给href
        link.href = window.URL.createObjectURL(blob)
        link.target = "_blank"
        // 设置文件名
        let nowTime = new Date()
        link.setAttribute("download", `导出课程${nowTime.getTime()}.xlsx`)
        // 将a标签添加到页面上
        document.body.appendChild(link)
        // 触发点击事件
        link.click()
        // 移除a标签
        document.body.removeChild(link)
    })
        .catch(err => {
            console.log(err, "导出失败");
        })
})
// const value1 = ref('')
// 添加弹框**************************************************************
// 添加&编辑的确定按钮
let id = ref()
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value === '添加渠道') {
                channeAdd(ruleForm).then(res => {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    })
                    getList()
                    dialogVisible.value = false
                })
            } else {
                channeEdits({
                    channelId: id.value,
                    ...ruleForm
                }).then(res => {
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                    getList()
                    dialogVisible.value = false
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
// center******************************************
const tableData = ref([])
const listParams = reactive({
    pageNum: 1,
    pageSize: 10
})
const total = ref()
onMounted(() => {
    getList()
})
function getList() {
    channelList(listParams).then(res => {
        console.log(res, "********************");
        tableData.value = res.rows
        total.value = res.total
    })
}
// 修改按钮
const editId = ref([])

const edit = ((val: any) => {
    if (val) {
        editId.value = val
    }
    title.value = "修改渠道"
    dialogVisible.value = true
    channeEdit(editId.value).then(res => {
        console.log(res, "2222222222");
        ruleForm.channelName = res.data.channelName
        ruleForm.status = res.data.status
        ruleForm.type = res.data.type
        ruleForm.remark = res.data.remark
        editId.value = res.data.channelId
        id.value = res.data.channelId
    })
})
// 删除按钮
const dialogVisibleDel = ref(false)
const del = ((val: any) => {
    let id = val ? val : editId.value
    ElMessageBox.confirm(
        `是否确认删除渠道编号为${id}的数据项`,
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            channelDel(id).then(res => {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            })
            dialogVisibleDel.value = false
            getList()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除失败',
            })
        })
})
// 多选框
// const selectable = (row: User) => ![1, 2].includes(row.id)
const handleSelectionChange = ((val: any) => {
    editId.value = []
    for (const item of val) {
        editId.value.push(item.channelId)
    }
})
// bottom*******************************
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
    listParams.pageNum = 1
    listParams.pageSize = val
    getList()
}
const handleCurrentChange = (val: number) => {
    listParams.pageNum = val
    getList()
}
</script>

<style lang="scss" scoped>
.main {
    padding: 20px;
}

// bottom***********
.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

.demo-pagination-block {
    display: flex;
    justify-content: right;
    padding: 30px 20px 20px;
}

.el-form-item {
    margin-right: 20px;
}
</style>